package com.itheima.appserver.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.itheima.appserver.config.MyAnno;
import com.itheima.appserver.config.MyThreadLocal;
import com.itheima.appserver.excepiton.ErrInfo;
import com.itheima.appserver.excepiton.MyEx;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        if (((HandlerMethod) handler).hasMethodAnnotation(MyAnno.class)) {
            //如果被该注解标注，则直接跳过判断token
            return true;
        }

        String token = request.getHeader("Authorization");
        //先校验token是否合法，正确
        JWT jwt = JWTUtil.parseToken(token);
        jwt.setKey(Constants.JWT_SECRET.getBytes());

        //校验token是否正确
        try {
            if (!jwt.verify()) {
                response.sendError(Integer.parseInt(ErrInfo.tokenError.getCode()), ErrInfo.tokenError.getMsg());
            }
        } catch (MyEx myEx) {
            response.sendError(Integer.parseInt(ErrInfo.tokenError.getCode()), ErrInfo.tokenError.getMsg());
        }
        //校验token是否过期
        if (!jwt.validate(0)) {
            response.sendError(Integer.parseInt(ErrInfo.tokenError.getCode()), ErrInfo.tokenError.getMsg());
        }

        Object uid = jwt.getPayload("uid");
        Object phoneNum = jwt.getPayload("phoneNum");
        MyThreadLocal.setUser(User.builder().id(Convert.toLong(uid)).mobile(Convert.toStr(phoneNum)).build());

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MyThreadLocal.reUser();
    }

}
